/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.device.servlet;

import cn.net.greenet.common.db_service.HibernateBaseDao;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiendpointbean;
import cn.net.greenet.db.bean.Messageincominglog;
import cn.net.greenet.device.logic.ByteConvert;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * 获取指定设备的静态信息
 *
 * @author LiuShang
 */
@WebServlet(name = "cn.net.greenet.device.servlet.GetDevStaticInfo", urlPatterns = {"/device/information/device_static"})
public class GetDevStaticInfo extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");//设备ID
        PrintWriter out = response.getWriter();
        if (id != null && id.matches("[0-9]*")) {
            try {
                Messageincominglog bean = null;
                SessionFactory sf = HibernateUtil.getSessionFactory();
                Session session = sf.openSession();
                session.clear();

//            SQLQuery query=session.createSQLQuery(sql);
                String hql = "From Messageincominglog  WHERE messageType=:messageType AND dpiendpointbean.id=" + id + " ORDER BY time DESC";
                HibernateBaseDao hbd = new HibernateBaseDao();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("messageType", "0xC5");
                List MessageInComingLogList = hbd.getListLimit(hql, 1, map, session);
//            Query query = session.createQuery("From Messageincominglog  WHERE messageType=:messageType AND dpiendpointbean.id=" + id + " ORDER BY time DESC");
//            query.setParameter("messageType", "0xc5");
//            query.setFirstResult(0).setMaxResults(1).list();
//            System.out.println("query:" + query.getQueryString());

//            ListService MessageInComingLogList = query.list();
//            System.out.println("MessageInComingLogList:" + MessageInComingLogList.size());
                Dpiendpointbean dpi = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(id));

                System.out.println("开启状态："+dpi.isEnabled());
                if (MessageInComingLogList.isEmpty() || !dpi.isEnabled()) {
                    JSONObject staticObiect = new JSONObject();
                    staticObiect.put("SoftwareVersion", "-");
                    staticObiect.put("device_enabled", dpi.isEnabled() ? "1" : "0");
                    int probeType = dpi.getProbeType();

                    staticObiect.put("Probe_Type", probeType + "");//DPI采集类型
                    if (0 == probeType) {
                        staticObiect.put("DeploySiteName", dpi.getDeploySiteName() + "");//本DPI设备部署站点名

                        staticObiect.put("IDC_HouseID", "-");//本DPI设备部署站点名称
                    } else if (1 == probeType) {

                        staticObiect.put("DeploySiteName", dpi.getDeploySiteName() + "");//本DPI设备部署站点名

                        staticObiect.put("IDC_HouseID", dpi.getIdcHouseId() + "");//本DPI设备部署站点名称
                    }
                    staticObiect.put("Deploy_Mode", "-");//本DPI设备在现网中的部署模式

                    staticObiect.put("Total_Capability", "-");//DPI设备总分析能力( 以Gbps为单位)，单向

                    staticObiect.put("SlotNum", "-");//DPI设备总槽位数  

                    staticObiect.put("PreProcSlotNum", "-");//DPI设备预处理模块占用槽位数

                    staticObiect.put("AnalysisSlotNum", "-");//DPI设备分析模块占用槽位数

                    staticObiect.put("GPSlotNum", "-");//DPI 通用 (General Purpose)模块占用槽位数
                    JSONArray PortsTypeNumArray = new JSONArray();
                    for (int i = 0; i < 1; i++) {
                        JSONObject PortsTypeNumObject = new JSONObject();
                        PortsTypeNumObject.accumulate("PortType", "-");//本DPI设备现有端口类型
                        PortsTypeNumObject.accumulate("Ports", '1');
                        JSONArray PortsArray = new JSONArray();
                        for (int j = 0; j < 1; j++) {
                            JSONObject PortsNumObject = new JSONObject();
                            PortsNumObject.put("PortNo", "-");//本端口的编号
                            PortsNumObject.put("PortDescription", "-");////本端口描述信息
                            PortsNumObject.put("M_LinkID", "-");//本端口监控链路编号
                            //本端口监控链路描述信息长度
                            PortsNumObject.put("M_LinkDesc", "-");//监控链路描述信息
                            PortsTypeNumArray.add(PortsNumObject);
                        }
                    }
                    staticObiect.put("Ports", PortsTypeNumArray);
                    out.println(staticObiect);
                } else if (MessageInComingLogList.size()>0){

                    JSONObject staticObiect = new JSONObject();
                    bean = (Messageincominglog) MessageInComingLogList.get(0);
                    System.out.println("静态-time-:" + bean.getTime());
                    byte[] msg = bean.getPacket();
                    int ptr = 18;
                    int SoftwareVersion = (int) ByteConvert.bytesToUint(Arrays.copyOfRange(msg, ptr, ptr + 4));//DPI软件版本号
                    ptr = ptr + 4;
                    staticObiect.put("SoftwareVersion", SoftwareVersion);
                    staticObiect.put("device_enabled", dpi.isEnabled() ? "1" : "0");
                    int Probe_Type = msg[ptr]&0xff;//DPI采集类型
                    ptr++;
                    staticObiect.put("Probe_Type", Probe_Type);
                    int DeploySiteNameLength = msg[ptr]&0xff;//本DPI设备部署站点名长度
                    ptr++;
                    String DeploySiteName = new String(Arrays.copyOfRange(msg, ptr, ptr + DeploySiteNameLength));//本DPI设备部署站点名
                    ptr = ptr + DeploySiteNameLength;
                    staticObiect.put("DeploySiteName", DeploySiteName);
                    int IDC_HouseID_Length = msg[ptr]&0xff;//EU 设 备 部 署 机 房HouseID的长度 
                    ptr++;
                    String IDC_HouseID = new String(Arrays.copyOfRange(msg, ptr, ptr + IDC_HouseID_Length));//本DPI设备部署站点名称
                    ptr = ptr + IDC_HouseID_Length;
                    staticObiect.put("IDC_HouseID", IDC_HouseID);

                    int Deploy_Mode = msg[ptr]&0xff;//本DPI设备在现网中的部署模式
                    ptr++;
                    staticObiect.put("Deploy_Mode", Deploy_Mode + "");

                    int Total_Capability = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//DPI设备总分析能力( 以Gbps为单位)，单向
                    ptr = ptr + 2;
                    staticObiect.put("Total_Capability", Total_Capability + "");//DPI设备总分析能力( 以Gbps为单位)，单向

                    int SlotNum = msg[ptr]&0xff;//DPI设备总槽位数  
                    ptr++;
                    staticObiect.put("SlotNum", SlotNum + "");

                    int PreProcSlotNum = msg[ptr]&0xff;//DPI设备预处理模块占用槽位数
                    ptr++;
                    staticObiect.put("PreProcSlotNum", PreProcSlotNum + "");

                    int AnalysisSlotNum = msg[ptr]&0xff;//DPI设备分析模块占用槽位数
                    ptr++;
                    staticObiect.put("AnalysisSlotNum", AnalysisSlotNum + "");

                    int GPSlotNum = msg[ptr]&0xff;//DPI 通用 (General Purpose)模块占用槽位数
                    ptr++;
                    staticObiect.put("GPSlotNum", GPSlotNum + "");

                    int PortsTypeNum = msg[ptr]&0xff;//本DPI设备所配备的端口类型数
                    ptr++;

                    JSONArray PortsTypeNumArray = new JSONArray();

                    for (int i = 0; i < PortsTypeNum; i++) {
                        JSONObject PortsTypeNumObject = new JSONObject();
                        int PortType = msg[ptr]&0xff;//本DPI设备现有端口类型
                        ptr++;

                        int PortsNum = msg[ptr]&0xff;//属于本类型的端口数
                        ptr++;
//                    JSONArray PortsArray = new JSONArray();
                        JSONArray PortsArray = new JSONArray();

                        for (int j = 0; j < PortsNum; j++) {
                            JSONObject PortsNumObject = new JSONObject();
                            PortsNumObject.accumulate("PortType", PortType + "");
                            int PortNo = msg[ptr]&0xff;//本端口的编号
                            ptr++;
                            PortsNumObject.put("PortNo", PortNo + "");

                            int PortDescLength = msg[ptr]&0xff;//本端口描述信息长度
                            ptr++;

                            String PortDescription = new String(Arrays.copyOfRange(msg, ptr, ptr + PortDescLength));//本端口描述信息
                            ptr = ptr + PortDescLength;
                            PortsNumObject.put("PortDescription", PortDescription);

                            int M_LinkID = msg[ptr]&0xff;//本端口监控链路编号
                            ptr++;
                            PortsNumObject.put("M_LinkID", M_LinkID + "");

                            int M_LinkDescLength = msg[ptr]&0xff;//本端口监控链路描述信息长度
                            ptr++;
                            String M_LinkDesc = new String(Arrays.copyOfRange(msg, ptr, ptr + M_LinkDescLength));//监控链路描述信息
                            ptr = ptr + M_LinkDescLength;
                            PortsNumObject.put("M_LinkDesc", M_LinkDesc);
                            PortsTypeNumArray.add(PortsNumObject);
                        }

                    }
                    staticObiect.put("Ports", PortsTypeNumArray);
                    out.println(staticObiect);
                }
                session.close();
            } catch (Exception e) {
                e.printStackTrace();
                out.println("[]");
            } finally {
                
            }
        } else {
            out.println("[" + id + "]");
        }
        out.close();
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
